package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.entity.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.entity.BaseAttrInfo;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
    implements BaseAttrInfoService{

    @Autowired
    BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseMapper.getBaseAttrAndValue(category1Id,category2Id,category3Id);
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //属性名保存到base_attr_info
        save(baseAttrInfo);
        //获取自增id
        Long id = baseAttrInfo.getId();

        //属性值保存到base_attr_value
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(id);
        }
        baseAttrValueService.saveBatch(attrValueList);
    }

    @Override
    public void updateAttrInfo(BaseAttrInfo baseAttrInfo) {
        //属性名修改到base_attr_info
        updateById(baseAttrInfo);
        //属性值修改到base_attr_value
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //判断前端数据与数据库数据  将前端未包含在内的数据删除
        //获取前端数据对应id集合
        ArrayList<Long> ids = new ArrayList<>();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if (baseAttrValue.getId() != null){
                ids.add(baseAttrValue.getId());
            }
        }
        //根据ids集合  删除数据
        baseAttrValueService.lambdaUpdate()
                .eq(BaseAttrValue::getAttrId, baseAttrInfo.getId())
                .notIn(BaseAttrValue::getId, ids)
                .remove();
        //判断值id 添加或修改
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if (baseAttrValue.getId() == null){
                //id空 添加
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueService.save(baseAttrValue);
            }else {
                //id有值 修改
                baseAttrValueService.updateById(baseAttrValue);
            }
        }
    }
}




